/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2021-12-04 17:42:59
 * 天凉好个秋
 */

import { Context, Next } from "koa";
import { verify } from "../../utils/auth";
import response from "../../utils/response";
import config from "../config";
import Permission from "../service/Permission";

// 角色资源列表
let roleResourcList = [];
// 获取所有角色资源列表
const getRoleResourceList = async () => {
  const data = await Permission.roleResourceList();
  roleResourcList = JSON.parse(JSON.stringify(data));
};

getRoleResourceList();

// 定时刷新权限数据缓存
setInterval(async () => {
  await getRoleResourceList()
}, config.permission.refreshTime);

// 权限校验中间件
const authMiddleware = async (ctx: Context, next: Next) => {
  const token = ctx.header["authorization"] || ctx.header["token"] as string;
  // 有token,验证权限
  if (token !== undefined && token !== "") {
    const { User, error } = verify(token);
    // token解析错误，直接返回
    if(error) return response.error(ctx, error)
    const hasPermission = await Permission.verifPermission(User?.id, ctx.path, roleResourcList);
    if (!hasPermission) return response.error(ctx, "无此权限", 401);
  } else {
    // 无token,设为游客权限
    const hasPermission = await Permission.verifPermission(false, ctx.path, roleResourcList);
    if (!hasPermission) return response.error(ctx, "无此权限", 401);
  }
  return next();
};

export default authMiddleware;
